package com.hschinese.pronunciation.widget;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.AppDataBean;
import com.hschinese.pronunciation.bean.AppResourceMap;
import com.hschinese.pronunciation.bean.LearnRecordBean;
import com.hschinese.pronunciation.bean.TestResultBean;
import com.hschinese.pronunciation.db.DBHelper;
import com.hschinese.pronunciation.interfaces.IseScoreInterface;
import com.hschinese.pronunciation.interfaces.LessonProgressInterface;
import com.hschinese.pronunciation.interfaces.NextLessonInterface;
import com.hschinese.pronunciation.interfaces.RecordStatusListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;
import com.hschinese.pronunciation.utils.Utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wo on 2015/11/10.
 */
public class ConsonantStudyView extends LinearLayout {
    private Context mContext = null;
    private View mView = null;
    private TextView mWordView;
    private TextView mConsWordView;
    private PlayControlView mPlayController;
    private RatingBar mRatingBar;

    private Cursor cursor;
    private List<AppDataBean> mDataList;
    private int currentPosition = 0;
    private int lessonType = 5;

    private LessonProgressInterface mListener = null;
    private NextLessonInterface mNextListener = null;
    private String mMp3SourceDir = null;

    public ConsonantStudyView(Context context) {
        super(context);
        mContext = context;
        mView = LayoutInflater.from(context).inflate(R.layout.single_syllable_practise_layout, null);
        mPlayController = (PlayControlView)mView.findViewById(R.id.single_syllable_play_control);
        mWordView = (TextView) mView.findViewById(R.id.single_syllable_text);
        mConsWordView = (TextView) mView.findViewById(R.id.single_syllable_text1);
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/hanyupinyin.ttf");
        mConsWordView.setTypeface(tf);
        mWordView.setTypeface(tf);
        if (lessonType == 7) {
            mConsWordView.setVisibility(View.GONE);
        }
        mRatingBar = (RatingBar)mView.findViewById(R.id.rating_bar);
        mRatingBar.setMax(100);
        mRatingBar.setProgress(0);
        mRatingBar.setVisibility(View.INVISIBLE);
        this.addView(mView);
    }

    public void initData() {
        mDataList = new ArrayList<AppDataBean>();
        if (lessonType == 5) {
            cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=? ", new String[]{lessonType + ""});
        } else if (lessonType == 7) {
            int groupID = Utils.getRandon(0, 4);
            Logger.e("xionghy - initData: " + groupID + " -- " + lessonType);
            cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=? and groupID=?", new String[]{lessonType + "", groupID + ""});
//            cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=? ", new String[]{lessonType + ""});
        }
        if (cursor != null)
            Logger.e("xionghy-cursor: " + cursor.getCount());
        while(cursor.moveToNext()) {
            AppDataBean d = new AppDataBean();
            d.setChinese(cursor.getString(cursor.getColumnIndex("chinese")));
            d.setPinyin(cursor.getString(cursor.getColumnIndex("pinyin")));
            d.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            d.setTone(cursor.getString(cursor.getColumnIndex("tone")));
            d.setAudioName(cursor.getString(cursor.getColumnIndex("audioName")));
            d.setPicName(cursor.getString(cursor.getColumnIndex("picName")));
            d.setType(cursor.getInt(cursor.getColumnIndex("type")));
            d.setGroupID(cursor.getInt(cursor.getColumnIndex("groupId")));
            d.setWeight(cursor.getInt(cursor.getColumnIndex("weight")));
            d.setId(cursor.getInt(cursor.getColumnIndex("id")));
            mDataList.add(d);
        }
        if (mDataList.size() <= 0) {
            Logger.e("获取到的数据为空。。。。");
            return;
        }
        Logger.e("xionghy - " + mDataList.size());
        Logger.e("xionghy: " + mDataList.get(currentPosition).toString());
        updateViewData();
    }

    private void updateViewData() {
        if (mListener != null) {
            mListener.setProgress(mDataList.size(), currentPosition);
        }
        mRatingBar.setProgress(0);
        mRatingBar.setVisibility(View.INVISIBLE);
        AppDataBean data = mDataList.get(currentPosition);
        if (lessonType == 5) {
            mMp3SourceDir = AppResourceMap.getMp3Fold(lessonType) + data.getPicName().replace("|", "") + ".mp3";
            mRatingBar.setVisibility(View.GONE);
        } else if (lessonType == 7) {
            mConsWordView.setVisibility(View.GONE);
            mPlayController.setChineseStr(data.getChinese());
            mPlayController.isUseScore(true);
            mPlayController.setScoreListener(new IseScoreInterface() {
                @Override
                public void scoreResult(float score) {
                    Logger.e("xionghy view -- score: " + score);
                    mRatingBar.setProgress((int)(score * 100 / 5));
                    mRatingBar.setVisibility(View.VISIBLE);
                    if (score <= 0.0f) {
                        // TODO 记录出错的单词
                        saveErrWord();
                    }
                }
            });
            mMp3SourceDir = AppResourceMap.getMp3Fold(lessonType) + data.getAudioName().replace("|", "") + ".mp3";
        }
        mPlayController.setStandardUrl(mMp3SourceDir);
        mPlayController.setPlayRecordVisibility(View.INVISIBLE);
        mPlayController.playStandard();
        if (lessonType == 5) {
            mConsWordView.setText(data.getPinyin().replace(data.getPicName(), ""));
            mWordView.setText(data.getPicName());
        } else {
            mWordView.setText(data.getPinyin());
        }
        if (lessonType == 5) {
            try {
                addLearnRecord(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void nextWord() {
        // TODO 数据切换，涉及到界面上文字和图片的切换
        mPlayController.resetProgressBar();
        currentPosition ++;
        if (currentPosition < mDataList.size()) {
            updateViewData();
        } else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
            int tipId = 0;
            if (lessonType == 5) {
                tipId = R.string.next_lesson_dialog_msg;
            } else {
                tipId = R.string.lesson_all_completer;
            }
            Utils.showDialog((Activity) mContext, tipId, lessonType, mNextListener);
        }
    }

    public void beforeWord() {
        if (currentPosition <= 0)
            return;
        mPlayController.resetProgressBar();
        currentPosition --;
        if (currentPosition < mDataList.size()) {
            updateViewData();
        } else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
//            mNextListener.onLessonChanged(lessonType - 1);
        }
    }

    public void setListener(LessonProgressInterface listener) {  mListener = listener; }

    public void setNextListener(NextLessonInterface listener) { mNextListener = listener; }

    public void setLessonType(int lesson) { lessonType = lesson; }

    public void setCurrentPosition(int pos) { currentPosition = pos; }

    public void onDestroy() {
        if (mPlayController != null) {
            mPlayController.destory();
        }
        if (cursor != null) cursor.close();
        SimpleRecordUtil.getInstance(mContext).stopPlayer();
        SimpleRecordUtil.getInstance(mContext).stopRecorder();
    }

    public void setRecordListener(RecordStatusListener l) { mPlayController.setRecordListener(l); }

    public void setVolumeListener(VolumeListener l) { mPlayController.setVolumeListener(l); }

    /**
     * tone fǔ|fu3,
     */
    private void saveErrWord() {
        AppDataBean data = mDataList.get(currentPosition);
        TestResultBean dataResult = new TestResultBean();
        String tone = data.getPinyin() + "|" + data.getAudioName();
        Cursor cursor = DBHelper.getInstance(mContext).query(DBHelper.TEST_RESULT_TABLE, " tone=? ", new String[]{tone});
        dataResult.setTone(tone);
        dataResult.setType(7);
        if (cursor.getCount() == 1) {
            cursor.moveToFirst();
            String to = cursor.getString(cursor.getColumnIndex("tone"));
            int wt = cursor.getInt(cursor.getColumnIndex("wrongTimes"));
            Logger.e("xionghy ： " + to + " @ " + " @ " + wt + " @ " + " @ " + tone);
            dataResult.setWrongTimes(wt++);
            DBHelper.getInstance(mContext).upgrade(DBHelper.TEST_RESULT_TABLE, dataResult);
            cursor.close();
        } else {
            dataResult.setWrongTimes(1);
            DBHelper.getInstance(mContext).insert(DBHelper.TEST_RESULT_TABLE, dataResult);
        }
    }

    private void addLearnRecord(AppDataBean data) {
        LearnRecordBean bean = new LearnRecordBean();
        bean.setChinese(data.getChinese());
        bean.setLearnedTimes(1);
        bean.setLearnType(lessonType + "");
        bean.setRecordID(data.getType() + "|" + data.getWeight());
        bean.setTimestamp(System.currentTimeMillis() + "");
        DBHelper.getInstance(mContext).insertLearnRecord(bean);
    }
}
